package com.zbkj.crmeb.task.plat.bieyang;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.common.CommonResult;
import com.crmeb.core.config.RestTemplateConfig;
import com.crmeb.core.exception.ExceptionCodeEnum;
import com.factory.TaskParamsDto;
import com.factory.TaskProcessEngineFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.PriceUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.AreaTypeEnum;
import com.zbkj.crmeb.enums.BusinessTypeEnums;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.by.dto.Price;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.plat.by.dto.Sku;
import com.zbkj.crmeb.plat.by.service.PlatProductService;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.Relation;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.tools.model.MoneyExchange;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.*;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 别样捞取
 *
 * @author: wsl
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("bieYangProduct9610Task")
@Configuration
@Slf4j
public class BieYangProduct9610Task extends AbstractPlatOperate<TaskParamsDto> implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(BieYangProduct9610Task.class);

    @Resource
    private PlatProductService platProductService;

    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Qualifier("byOrderProductHandler")
    @Autowired
    private OrderProductInterface orderProductInterface;

    @Value("${by.plat.url}")
    private String platUrl;

    private static String platKey;
    @Value("${by.plat.key}")
    public void setKey(String key) {
        platKey = key;
    }

    private static String envValue;
    @Value("${spring.profiles.active}")
    public void setEnv(String env) {
        envValue = env;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        if (Objects.equals(envValue,"test")||Objects.equals(envValue,"dev")){
//            log.info("当前环境暂不推送商品, env:{}",envValue);
//            return;
//        }
//        // 整个线程轮询
//        new Thread(()->{
//            while (true){
//                try {
////                    TaskProcessEngineFactory.executeTask();
////                    checkByProductStockV2();
////                    checkByProductPriceV2();
//                    Thread.sleep(RandomUtils.nextInt(1000,3000));
//                }catch (Exception e){
//                    log.error("商品轮询任务执行失败");
//
//                }
//            }
//        }).start();
    }

    @Override
    public Result execute(TaskParamsDto taskParamsDto) {
        taskParamsDto.getPlatProductRequest().setSyncTask(false);
        CommonResult<List<String>> commonResult = platProductService.pushProduct(taskParamsDto.getPlatProductRequest()
                , Integer.valueOf(StringUtils.isNotBlank(taskParamsDto.getMerId())?taskParamsDto.getMerId():"126"));
        if (commonResult.getCode() == ExceptionCodeEnum.SUCCESS.getCode()){
            return Result.getSuccessResult();
        }
        if (commonResult.getCode() != ExceptionCodeEnum.SUCCESS.getCode()){
//            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"推送商品失败,productId:+"+taskParamsDto.getPlatProductRequest().getProductId()+",:"+commonResult.getMessage());
            log.error("推送商品失败,productId:{},:{}",taskParamsDto.getPlatProductRequest().getProductId(),commonResult.getMessage());
        }
        return Result.getFailureResult("execute error",commonResult.getMessage());
    }

//    @XxlJob("byDownProduct")
//    public void downProduct(){
//        List<Integer> merIds = new ArrayList<>();
//        merIds.add(126);
////        merIds.add(18);
//        BusinessTypeEnums productRelationsType = null;
//        BusinessTypeEnums skuRelationsType = null;
//        for (Integer merId : merIds) {
//            if (merId == 126 || merId == 18){
//                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_BY;
//                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_BY;
//                downProduct(merId,productRelationsType,skuRelationsType);
//            }
//        }
//    }
//
//    public void downProduct(Integer merId,BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType){
//        try {
//            // mock个请求
//            MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
//            mockHttpServletRequest.addHeader("mer_id",String.valueOf(merId));
//            ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
//            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
//            // 捞上架数据
//            int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
//                    .eq(Relation::getBusinessType, productRelationsType.getCode()));
//            if (count == 0){
//                logger.error("别样下架商品,未扫描到已上架商品");
//                return;
//            }
//            int maxPage = (count+499)/500;
//            int pageNo = 1;
//            while (pageNo<=maxPage){
//                Page<Relation> page = PageHelper.startPage(pageNo, 500);
//                try {
//                    relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
//                            .eq(Relation::getBusinessType,productRelationsType.getCode()).orderByDesc(Relation::getId));
//                    List<Relation> productRelations = page.getResult();
//                    if (CollectionUtils.isEmpty(productRelations)){
//                        throw new RuntimeException("数据查询异常");
//                    }
//
//                }catch (Exception e){
//                    logger.error("别样下架商品,下架异常",e);
//                }finally {
//                    pageNo++;
//                }
//            }
//        }catch (Exception e){
//            logger.error("别样下架商品异常:",e);
//        }finally {
//            RequestContextHolder.resetRequestAttributes();
//        }
//    }


    @XxlJob("checkByProductPrice9610")
    public void checkByProductPriceV2(){
        List<Integer> merIds = new ArrayList<>();
        merIds.add(126);
//        merIds.add(18);
        BusinessTypeEnums productRelationsType = null;
        BusinessTypeEnums skuRelationsType = null;
        for (Integer merId : merIds) {
            if (merId == 126 || merId == 18){
                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_BY;
                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_BY;
                checkByProductPrice(merId,productRelationsType,skuRelationsType);
            }
        }
    }


    public void checkByProductPrice(Integer merId, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType){
        try {
            // mock个请求
            MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
            mockHttpServletRequest.addHeader("mer_id",String.valueOf(merId));
            ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
            RequestContextHolder.setRequestAttributes(servletRequestAttributes);
            // 捞上架数据
            int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
                    .eq(Relation::getBusinessType, productRelationsType.getCode()));
            if (count == 0){
                logger.error("别样商家商品检查任务,未扫描到已上架商品");
                return;
            }
            // 需要更新价格sku
            List<StoreProductAttrValue> needUpdateSkus = new ArrayList<>();
            int maxPage = (count+499)/500;
            int pageNo = 1;
            while (pageNo<=maxPage){
                Page<Relation> page = PageHelper.startPage(pageNo, 500);
                try {
                    relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
                            .eq(Relation::getBusinessType,productRelationsType.getCode()).orderByDesc(Relation::getId));
                    List<Relation> productRelations = page.getResult();
                    if (CollectionUtils.isEmpty(productRelations)){
                        throw new RuntimeException("数据查询异常");
                    }
                    // 检查sku信息
                    List<Integer> productIds = productRelations.stream().map(k->Integer.valueOf(k.getBusinessCode())).collect(Collectors.toList());
                    List<StoreProductAttrValue> attrValues = storeProductAttrValueService.listRelationInfoByProductId(productIds, skuRelationsType);
                    if (CollectionUtils.isEmpty(attrValues)){
                        continue;
                    }
                    Map<Integer, List<StoreProductAttrValue>> skuMap = attrValues.stream().collect(Collectors.groupingBy(StoreProductAttrValue::getProductId));
                    List<StoreProduct> storeProducts = storeProductService.listByIds(productIds);
                    Map<Integer, StoreProduct> productMap = storeProducts.stream().collect(Collectors.toMap(StoreProduct::getId, v -> v));
                    Map<Integer, Relation> productRelationMap = productRelations.stream().collect(Collectors.toMap(k -> Integer.valueOf(k.getBusinessCode()), v -> v));
                    for (Map.Entry<Integer, List<StoreProductAttrValue>> entry : skuMap.entrySet()) {
                        Integer productId = entry.getKey();
                        List<StoreProductAttrValue> skus = entry.getValue();
                        StoreProduct storeProduct = productMap.get(productId);
                        Relation relation = productRelationMap.get(productId);
                        if (CollectionUtils.isEmpty(skus) || null == storeProduct){
                            continue;
                        }
                        priceUtil.calcProductValuePrice(skus, merId, storeProduct, AreaTypeEnum.CN.getType(), null, false, null, true, null);
                        // 过滤需要更新价格的sku
                        List<StoreProductAttrValue> needUpdatePriceList = needUpdatePriceProducts(skus,relation,productRelationsType,skuRelationsType);
                        if (CollectionUtils.isNotEmpty(needUpdatePriceList)){
                            needUpdateSkus.addAll(needUpdatePriceList);
                        }

                    }
                }catch (Exception e){
                    logger.error("别样商家商品价格检查任务,查询商品异常",e);
                }finally {
                    pageNo++;
                }
            }
            if (CollectionUtils.isNotEmpty(needUpdateSkus)){
                doUpdateSkusPrice(needUpdateSkus);
            }
        }catch (Exception e){
            logger.error("别样商家商品价格检查任务,查询商品异常:",e);
        }finally {
            RequestContextHolder.resetRequestAttributes();
        }


    }
    private void doUpdateSkusPrice(List<StoreProductAttrValue> updateSkus) {

        try {
            for (StoreProductAttrValue skus : updateSkus) {
                String srcPrice = skus.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE);
                String merchantProductId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_PRODUCT_ID);
                Sku sku = new Sku();
                int price = Integer.parseInt(skus.getPushRelation().getFeature(ByCommonConstant.NEW_PLAT_ORIGINAL_PRICE));
                Price salePrice = new Price();
                salePrice.setCurrency("USD");
                salePrice.setValue(price);
                sku.setSupplyPrice(salePrice);
                sku.setStockNum(skus.getStock());
                String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
                // 随机休眠一下，下次做下限流
                Thread.sleep(RandomUtils.nextInt(10,100));
                String post = "";
                try {
                    post = post(String.format(platUrl + "/inventory/api/v1/products/%s/skus/%s", merchantProductId, skuId), JSON.toJSONString(sku));
                }catch (Exception e){
                    log.error("更新价格请求接口失败:{}",e.getMessage(),e);
                }
                Sku platSku = JSON.parseObject(post, Sku.class);
                if (null != platSku && StringUtils.isNotBlank(platSku.getId())){
                    skus.getPushRelation().addFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE,String.valueOf(sku.getSupplyPrice().getValue()));
                    relationService.updateById(skus.getPushRelation());
                }
//                DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,String.format("别样更新价格，原价:%s ,更新价格:%s ,接口返回:%s",srcPrice,price,post));
                logger.error("别样更新价格，原价:{} ,更新价格:{} ,接口返回:{}",srcPrice,price,post);
            }
        }catch (Exception e){
            log.error("更新sku价格异常:",e);
        }
    }

    private List<StoreProductAttrValue> needUpdatePriceProducts(List<StoreProductAttrValue> attrValues, Relation relation, BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType) {
        // 移除掉库存为0
        attrValues.removeIf(k->k.getStock()<=0);
        if (CollectionUtils.isEmpty(attrValues)){
            return null;
        }
        // 金额加上一二段费用
        attrValues.forEach(v->v.setPrice(getValidPrice(v.getPrice()).add(getValidPrice(v.getFirstPrice())).add(getValidPrice(v.getSecondPrice()))));
        // 库存>0且价格最低的sku
        Map<String, StoreProductAttrValue> sortMap = attrValues.stream().filter(k->k.getStock()>0).collect(Collectors.toMap(StoreProductAttrValue::getSuk, v -> v, (v1, v2) -> {
            if (v1.getPrice().compareTo(v2.getPrice()) <= 0) {
                return v1;
            }
            return v2;
        }));
        // 获取上架的sku
        List<StoreProductAttrValue> srcSkus = storeProductAttrValueService.
                listRelationInfoByProductId(Collections.singletonList(Integer.valueOf(relation.getBusinessCode())),skuRelationsType);
        // 移除掉没有推送关联或者未上架的sku
        srcSkus.removeIf(k->null == k.getPushRelation() || !Objects.equals(k.getPushRelation().getSubCode(),ByCommonConstant.BY_UP));
        if (CollectionUtils.isEmpty(srcSkus)){
            return null;
        }
        List<StoreProductAttrValue> needUpdateList = new ArrayList<>();
        // 获取最终需要更新的数据
        for (StoreProductAttrValue srcSku : srcSkus) {
            String suk = srcSku.getSuk();
            // 用规格来匹配
            if (!sortMap.containsKey(suk)){
                continue;
            }
            StoreProductAttrValue sku = sortMap.get(suk);
            BigDecimal baseExchange = new BigDecimal("7.0");
            MoneyExchange moneyExchange = moneyExchangeService.getById(12);
            if (null != moneyExchange && StringUtils.isNotBlank(moneyExchange.getBankConversionPri())){
                baseExchange = new BigDecimal(moneyExchange.getBankConversionPri());
            }
            // 平台原价为空或者差价绝对值超过了固定点
            boolean flag = StringUtils.isBlank(srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE))
                    || outPriceThreshold(srcSku.getPushRelation().getFeature(ByCommonConstant.PLAT_ORIGINAL_PRICE),sku.getPrice(),baseExchange);
            if (flag){
                srcSku.getPushRelation().addFeature(ByCommonConstant.NEW_PLAT_ORIGINAL_PRICE,String.valueOf(sku.getPrice().divide(baseExchange, 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN).intValue()));
                srcSku.getPushRelation().addFeature(ByCommonConstant.MERCHANT_PRODUCT_ID,relation.getFeature(ByCommonConstant.MERCHANT_PRODUCT_ID));
                srcSku.getPushRelation().addFeature(ByCommonConstant.PUSH_PRICE,String.valueOf(sku.getPrice()));
                needUpdateList.add(srcSku);
            }
        }
        return needUpdateList;
    }

    private boolean outPriceThreshold(String platPrice, BigDecimal price,BigDecimal baseExchange) {
        String newPrice = String.valueOf(price.divide(baseExchange, 2, RoundingMode.DOWN).multiply(BigDecimal.valueOf(100L)).setScale(2, RoundingMode.DOWN).intValue());
        // 最大差值
        double maxDiff = Integer.parseInt(platPrice) * 0.02;
        return Math.abs(Integer.parseInt(newPrice) - Integer.parseInt(platPrice)) > maxDiff;
    }

    private BigDecimal getValidPrice(BigDecimal value){
        return null == value || value.compareTo(BigDecimal.ZERO)<=0? BigDecimal.ZERO:value;
    }

    @XxlJob("checkByProductStock9610")
    public void checkByProductStockV2(){
        List<Integer> merIds = new ArrayList<>();
        merIds.add(126);
//        merIds.add(18);
        BusinessTypeEnums productRelationsType = null;
        BusinessTypeEnums skuRelationsType = null;
        for (Integer merId : merIds) {
            if (merId == 126 || merId==18){
                productRelationsType = BusinessTypeEnums.PUSH_PRODUCT_PLAT_OF_BY;
                skuRelationsType = BusinessTypeEnums.PUSH_SKU_PLAT_OF_BY;
                checkByProductStock(merId,productRelationsType,skuRelationsType);
            }
        }
    }

    public void checkByProductStock(Integer merId,BusinessTypeEnums productRelationsType, BusinessTypeEnums skuRelationsType){
        // 捞上架数据
        int count = relationService.count(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
                .eq(Relation::getBusinessType, productRelationsType.getCode()));
        if (count == 0){
            logger.error("别样商家商品检查任务,未扫描到已上架商品");
            return;
        }
        int maxPage = (count+499)/500;
        int pageNo = 1;
        while (pageNo<=maxPage){
            Page<Relation> page = PageHelper.startPage(pageNo, 500);
            try {
                relationService.list(Wrappers.<Relation>lambdaQuery().eq(Relation::getSubCode, ByCommonConstant.BY_UP)
                        .eq(Relation::getBusinessType,productRelationsType.getCode()).orderByDesc(Relation::getId));
                List<Relation> productRelations = page.getResult();
                if (CollectionUtils.isEmpty(productRelations)){
                    throw new RuntimeException("数据查询异常");
                }
                // 检查sku信息
                List<Integer> productIds = productRelations.stream().map(k->Integer.valueOf(k.getBusinessCode())).collect(Collectors.toList());

                List<StoreProductAttrValue> attrValues = storeProductAttrValueService.listRelationInfoByProductId(productIds, skuRelationsType);
                if (CollectionUtils.isEmpty(attrValues)){
                    throw new RuntimeException("SKU数据为空");
                }
                Map<Integer, List<StoreProductAttrValue>> map = filterSkuInfos(attrValues);
                if (MapUtils.isEmpty(map)){
                    continue;
                }
                for (Relation relation : productRelations) {
                    Integer productId = Integer.valueOf(relation.getBusinessCode());
                    if (!map.containsKey(productId)){
                        continue;
                    }
                    List<StoreProductAttrValue> storeProductAttrValues = map.get(productId);
                    updateProduct(relation.getFeature(ByCommonConstant.MERCHANT_PRODUCT_ID),storeProductAttrValues);
                }
            }catch (Exception e){
                logger.error("别样商家商品检查任务,查询商品异常",e);
            }finally {
                pageNo++;
            }
        }
    }

    private void updateProduct(String merchantProductId, List<StoreProductAttrValue> storeProductAttrValues) {
        if (CollectionUtils.isEmpty(storeProductAttrValues)){
            return;
        }
        List<StoreProductAttrValue> downSkus = new ArrayList<>();
        List<StoreProductAttrValue> updateSkus = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            if (storeProductAttrValue.getStock() <= 0){
                downSkus.add(storeProductAttrValue);
                continue;
            }
            updateSkus.add(storeProductAttrValue);
        }
        try {
            if (CollectionUtils.isNotEmpty(downSkus)){
                doDownSkus(merchantProductId,downSkus);
            }
        }catch (Exception e){
            logger.error("商品下架异常:",e);
        }
        try {
            if (CollectionUtils.isNotEmpty(updateSkus)){
                doUpdateSkus(merchantProductId,updateSkus);
            }
        }catch (Exception e){
            logger.error("更新商品库存异常:",e);
        }

    }

    private void doUpdateSkus(String merchantProductId, List<StoreProductAttrValue> updateSkus) {
        for (StoreProductAttrValue skus : updateSkus) {
            Sku sku = new Sku();
            sku.setStockNum(skus.getStock());
            sku.setStatus(ByCommonConstant.PLAT_AVAILABLE);
            try {
                Thread.sleep(RandomUtils.nextInt(10,100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
            String post = post(String.format(platUrl + "/inventory/api/v1/products/%s/skus/%s", merchantProductId, skuId), JSON.toJSONString(sku));
            Sku platSku = JSON.parseObject(post, Sku.class);
            if (null != platSku && StringUtils.isNotBlank(platSku.getId())){
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK,String.valueOf(skus.getStock()));
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.BY_UP.getCode());
                relationService.updateById(skus.getPushRelation());
            }
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样更新库存返回:"+post);
            logger.error("别样更新库存返回:{}",post);
        }

    }

    private void doDownSkus(String merchantProductId,List<StoreProductAttrValue> downSkus) {
        for (StoreProductAttrValue skus : downSkus) {
            Sku sku = new Sku();
            sku.setStatus(ByCommonConstant.PLAT_UNAVAILABLE);
            sku.setStockNum(0);
            String skuId = skus.getPushRelation().getFeature(ByCommonConstant.MERCHANT_SKU_ID);
            try {
                Thread.sleep(RandomUtils.nextInt(10,100));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            String post = post(String.format(platUrl + "/inventory/api/v1/products/%s/skus/%s", merchantProductId, skuId), JSON.toJSONString(sku));
            Sku platSku = JSON.parseObject(post, Sku.class);
            if (null != platSku && StringUtils.isNotBlank(platSku.getId())){
                skus.getPushRelation().addFeature(ByCommonConstant.ORIGIN_STOCK,"0");
                skus.getPushRelation().addFeature(ByCommonConstant.PUSH_PLAT,"N");
                skus.getPushRelation().setSubCode(PlatPushStatusEnums.BY_DOWN.getCode());
                relationService.updateById(skus.getPushRelation());
            }
            DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样sku下架返回:"+post);
            logger.error("别样sku下架返回:{}",post);
        }

    }


    private Map<Integer,List<StoreProductAttrValue>> filterSkuInfos(List<StoreProductAttrValue> attrValues) {
        Iterator<StoreProductAttrValue> iterator = attrValues.iterator();
        Map<Integer,List<StoreProductAttrValue>> map = new HashMap<>();
        while (iterator.hasNext()){
            StoreProductAttrValue attrValue = iterator.next();
            // 没有推送关系，没有上架标记，库存大于0并且上架库存和当前库存相等
            boolean flag = attrValue.getPushRelation() == null || !Objects.equals(attrValue.getPushRelation().getSubCode(),ByCommonConstant.BY_UP)
                    || (Objects.equals(attrValue.getStock(),Integer.valueOf(attrValue.getPushRelation().getFeature(ByCommonConstant.ORIGIN_STOCK))));
            if (flag){
                iterator.remove();
                continue;
            }
            map.computeIfAbsent(attrValue.getProductId(),v->new ArrayList<>()).add(attrValue);
        }
        return map;
    }


    public static String post(String url, String params) {
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));
        return request(url, params, header, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }
    public static String post(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }

    /**
     * http请求
     *
     * @param url
     * @param params    请求参数
     * @param headers   请求头
     * @param method    请求方式
     * @param mediaType 参数类型
     * @return
     */
    public static String request(String url, Object params, MultiValueMap<String, String> headers, HttpMethod method, MediaType mediaType) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        RestTemplate client = new RestTemplate();
        // header
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            httpHeaders.addAll(headers);
        }
        // 提交方式：表单、json
        httpHeaders.setContentType(mediaType);
        HttpEntity<Object> httpEntity = new HttpEntity(params, httpHeaders);
        ResponseEntity<String> response = client.exchange(url, method, httpEntity, String.class);
        return response.getBody();
    }


}
